<!--
 * @Author: 1086 cchcc@qq.com
 * @Date: 2024-04-22 10:31:18
 * @LastEditors: 1086 cchcc@qq.com
 * @LastEditTime: 2024-05-16 15:25:55
 * @FilePath: \erp\ui\pos\src\views\pos\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 主界面布局 -->
  <lay-layout class="example">
    <lay-side style="min-width: 350px; min-height: calc(100vh - 60px)">
      <div id="vv">
        <div style="min-width: 350px; height: 90px">
          <div class="vv789">
            <span>当班:欧阳张三</span>
            <span>班次:A班</span>
            <span>会员:张*丰</span>
          </div>
          <div class="vv789">
            <span style="width: 66%; background-color: #fff">单号:{{ home_order_db.dbid }}</span>
            <span>挂单:2</span>
          </div>
          <div class="vv789">
            <span>上单合计:9999</span>
            <span>上单实收:100000</span>
            <span>上单找零:111</span>
          </div>
        </div>
        <!-- 商品列表 -->
        <div>
          <lay-table style="height: calc(100vh - 150px); max-height: calc(100vh - 150px)" size="sm" :columns="columns"
            :data-source="home_order_db.goods_li" :rowStyle="rowStyle">
            <template #barcode="{ data }">
              <span @click="barcode_c(data)" style="color: rgb(255, 104, 34)">
                {{ data.barcode }}
              </span>
            </template>
            <!--数量点击-->
            <template #number="{ data }">
              <!-- 点击修改数量表格触发 -->
              <div style="width: 100%; height: 100%;border-bottom: 1px solid" @click="changeQuantilty(data)">
                <span>{{ data.number }}</span>
              </div>
            </template>
            <template #prc_sale_actual="{ data }">
              <!-- 实际零售价 -->
              <span>{{ data.prc_sale_actual }}</span>

            </template>

            <template #prc_sale_actual_sum="{ data }">
              <!-- 实际零售价小计 -->
              <span class="prc_sale_actual_sum">{{ data.prc_sale_actual_sum }}</span>

            </template>

            <template #operator="{ data }">
              <!-- 删除某个商品 -->
              <lay-button type="warm" fluid @click="deleteProductMethod(data)">
                <lay-icon type="layui-icon-close"></lay-icon>
              </lay-button>
            </template>

            <template v-slot:footer>
              <lay-input v-model="QR_val" :allow-clear="true" @input="changeQR_val" placeholder="请输入条码" >
                <template #suffix>
                  <lay-icon type="layui-icon-keyboard" @click="QR_keyboard"></lay-icon>

                </template>
                <template v-slot:append>
                  <span @click="QR_event">确认</span>
                </template>
              </lay-input>
            </template>
          </lay-table>
        </div>







      </div>
    </lay-side>

    <lay-side class="side2" style="max-width: 70px !important">
      <div class="cc">
        <lay-ripple><span @click="click_LI('退货')">退货</span></lay-ripple>
        <lay-ripple><span @click="click_LI('开钱箱')">开钱箱</span></lay-ripple>
        <lay-ripple><span @click="click_LI('开新单')">开新单</span></lay-ripple>
        <lay-ripple><span @click="click_LI('挂取单')">挂取单</span></lay-ripple>
        <lay-ripple><span @click="click_LI('历史单')">历史单</span></lay-ripple>
        <lay-ripple><span>打折</span></lay-ripple>
        <lay-ripple><span>赠送</span></lay-ripple>
        <lay-ripple><span>查会员</span></lay-ripple>
        <lay-ripple><span>查商品</span></lay-ripple>
        <lay-ripple><span>----</span></lay-ripple>
        <lay-ripple><span>··更多</span></lay-ripple>
      </div>
    </lay-side>

    <lay-layout>
      <lay-header>
        <div class="dd">
          <lay-ripple><span>按分类</span></lay-ripple>
          <lay-ripple><span>常用</span></lay-ripple>
          <lay-ripple><span>按促销</span></lay-ripple>
          <lay-ripple><span>无条码</span></lay-ripple>
          <lay-ripple><span>高销量</span></lay-ripple>
          <lay-ripple><span>高库存</span></lay-ripple>
          <lay-ripple><span>预设1</span></lay-ripple>
        </div>
      </lay-header>
      <lay-body>
        <div style="width: 100%">
          <div class="tab_a" style="height: calc(100vh - 180px)">
            <lay-tab type="card" v-model="tab_a_model" style="padding: 0; margin: 0">
              <lay-tab-item title="选项一" id="1">
                <div class="p_list">
                  <div class="p_main" v-for="p in products" :key="p.goods_dbid" @click="selectProduct(p)">
                    <div class="p_main_header">
                      {{ p.goods_name }}
                    </div>
                    <div class="p_main_body">
                      <div class="p_main_body_img">
                        <img src="/src/assets/imgs/bskl.jpg" alt="" />
                      </div>
                      <div class="p_main_body_fotter">
                        <i class="layui-icon">&#xe65e;</i>
                        <span>{{ p.prc_sale }}</span>/
                        <span>{{ p.unit }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </lay-tab-item>
              <lay-tab-item title="选项二" id="2">
                <div class="body2">
                  <div class="vc">
                    <lay-ripple>
                      <span class="vc1">1234567895</span>
                      <span class="vc2">我是可是可是可是可口可乐250G/瓶</span>
                      <span class="vc3">
                        <span class="vc3a">￥4.5</span>
                        <span class="vc3b">瓶</span>
                      </span>
                    </lay-ripple>
                  </div>
                  <div class="vc">
                    <lay-ripple>
                      <span class="vc1">1234567895</span>
                      <span class="vc2">我是可是可是可是可口可乐250G/瓶</span>
                      <span class="vc3">
                        <span class="vc3a">￥4.5</span>
                        <span class="vc3b">瓶</span>
                      </span>
                    </lay-ripple>
                  </div>
                  <div class="vc">
                    <lay-ripple>
                      <span class="vc1">1234567895</span>
                      <span class="vc2">我是可是可是可是可口可乐250G/瓶</span>
                      <span class="vc3">
                        <span class="vc3a">￥4.5</span>
                        <span class="vc3b">瓶</span>
                      </span>
                    </lay-ripple>
                  </div>
                  <div class="vc">
                    <lay-ripple>
                      <span class="vc1">1234567895</span>
                      <span class="vc2">我是可是可是可是可口可乐250G/瓶</span>
                      <span class="vc3">
                        <span class="vc3a">￥4.5</span>
                        <span class="vc3b">瓶</span>
                      </span>
                    </lay-ripple>
                  </div>
                </div>
              </lay-tab-item>
            </lay-tab>
          </div>
        </div>
      </lay-body>
      <lay-footer>
        <div class="btn_head">
          <lay-button size="lg" type="danger" @click="click_LI('打印')">打印</lay-button>
          <lay-button size="lg" type="danger" @click="click_LI('测试')">测试</lay-button>
          <lay-button size="lg" type="danger" @click="click_LI('更多')">···更多</lay-button>
        </div>
        <div class="btn_foot">
          <lay-button size="lg" type="danger" @click="settlement">结算</lay-button>
        </div>
      </lay-footer>
    </lay-layout>
  </lay-layout>
  <lay-footer>
    <div class="footer_d">
      <div>
        <span style="display: block"><lay-select v-model="printerSYS.printer_checked_name"
            :items="printerSYS.printer_List" :options="printerSYS.printer_List" size="xs" name="PrinterList"
            @change="change_PrinterList"></lay-select></span>
        <span style="display: block">--</span>
        <span style="display: block">--</span>
      </div>
      <div>
        <span style="display: block">--</span>
        <span style="display: block">--</span>
        <!-- 打印机列表 -->
      </div>
      <div style="text-align: right">
        <span style="display: block">--</span>
        <span style="display: block"><a href="https://sp.6-7-8-9.com/#/login" target="_blank">后台管理</a></span>
        <span style="display: block">xp收银管理系统@ 服务热线:13800138000 / 010-1234567</span>
      </div>
    </div>
  </lay-footer>

  <lay-layer v-model="quantiltyVisible" :shade="false" :area="['400px']" :btn="quntiltyAction" title="数量">
    <div class="t_quantilty_input">
      <lay-row space="10">
        <lay-col md="8">
          <div class="grid-demo">
            <span>数量：</span>
          </div>
        </lay-col>
        <lay-col md="12">
          <div class="grid-demo">
            <lay-input v-model="selectedProduct.number" keyboard="true" @input="quantiltyChange"
              placeholder="请输入数量"></lay-input>
          </div>
        </lay-col>
      </lay-row>

      <keyboard :transitionTime="'0.5s'" :maxQuantify="10" :showKeyboard="showKeyboard" :mode="'num'" float
        :blurHide="true">
      </keyboard>
    </div>
  </lay-layer>


  <!--结算窗口-->
  <lay-layer v-model="window_pay_show" :shadeClose="false" :closeBtn="false" :shadeOpacity="0.5"
    :area="['800px', '580px']" :title="home_order_db.dbid">
    <window_pay @windowClose_0="windowClose" :order_db="home_order_db" @pay_res="pay_res">
    </window_pay>
  </lay-layer>

  <!-- 历史单-列表窗口 -->
  <lay-layer type="1" v-model="window_show_past_order" :shadeClose="false" :area="['600px', '400px']"
    :btn="btn_past_order" title="历史单">
    <lay-table size="sm" id="id" :autoColsWidth="true" height="290px" @row="past_order_row"
      :columns="Past_Order_List_columns" :data-source="Past_Order_List_dataSource"></lay-table>
  </lay-layer>
  <!-- 历史单-详细内容窗口 -->
  <lay-layer :maxmin="true" v-model="window_show_past_order_content" :shadeClose="false" :area="['600px', '400px']"
    :btn="btn_past_order_content" title="历史单-内容">
    <lay-tab v-model="tab_past_order_content" @change="change_tab_past_order_content">
      <lay-tab-item title="单头信息" id="order_db">
        <div style="padding:0px 10px 0px 10px">
          <lay-row space="12">
            <lay-col md="12">
              <lay-input v-model="order_db.id">
                <template #prepend="{ disabled }">{{ order_db_alias.id }}</template>
              </lay-input>
            </lay-col>
            <lay-col md="12">
              <!-- 单据编号 -->
              <lay-input v-model="order_db.dbid">
                <template #prepend="{ disabled }">{{ order_db_alias.dbid }}</template>
              </lay-input>
            </lay-col>

            <lay-col md="12">
              <!-- 单据状态 -->
              <lay-input v-model="order_db.state_mp">
                <template #prepend="{ disabled }">{{ order_db_alias.state }}</template>
              </lay-input>
            </lay-col>
            <lay-col md="12">
              <!-- 单据类型 -->
              <lay-input v-model="order_db.type_mp">
                <template #prepend="{ disabled }">{{ order_db_alias.type }}</template>
              </lay-input>
            </lay-col>
            <lay-col md="12">
              <!-- 门店操作员 -->
              <lay-input v-model="order_db.operator">
                <template #prepend="{ disabled }">{{ order_db_alias.operator }}</template>
              </lay-input>
            </lay-col>

          </lay-row>
        </div>
      </lay-tab-item>
      <lay-tab-item title="商品信息" id="order_db_goods">
        <div style="padding:0px 10px 0px 10px">
          <lay-table size="sm" id="id" height="220px" :columns="past_order_goods_columns"
            :data-source="past_order_goods_dataSource"></lay-table>
        </div>
      </lay-tab-item>
      <lay-tab-item title="支付信息" id="order_db_pay">
        <div style="padding:0px 10px 0px 10px">
          <lay-table size="sm" id="id" height="220px" :columns="past_order_pay_columns"
            :data-source="past_order_pay_dataSource"></lay-table>
        </div>
      </lay-tab-item>
    </lay-tab>
  </lay-layer>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { toRaw } from "@vue/reactivity";
import { layer } from "@layui/layui-vue";
import { io } from "socket.io-client";
import { HTTP_newDbid, HTTP_saveOrder, HTTP_homeOrderId, HTTP_pastOrderList, HTTP_pastOrderId } from "@/apis/cashierApi";
import XEUtils from "xe-utils";
import window_pay from "./pay/windowPay.vue";
import keyboard from "@/components/keyboard/keyboardIndex.vue";

const showKeyboard = ref(false);
const showKeyboard1 = ref(false);

const quantiltyVisible = ref(false); //数量弹窗
const window_pay_show = ref(false); //结算弹框



// 当前操作的订单数据
const home_order_db = ref({
  dbid: "000000000000000000",//当前销售单号
  sign: "",//当前销售单签名串
  goods_li: [],//商品列表
});

//结算回调事件
const settlementAction = ref([
  {
    text: "确定",
    callback: () => {
      console.log("结算");
      window_pay_show.value = false;
    },
  },
  {
    text: "取消",
    callback: () => {
      console.log("取消");
      window_pay_show.value = false;
    },
  },
]);

//删除某个商品
const deleteProductMethod = (product) => {
  console.log("删除商品", product);
  layer.confirm("是否要删除该商品？", {
    btn: [
      {
        text: "是",
        callback: (id) => {
          deleteProduct(product);
          layer.close(id);
        },
      },
      {
        text: "否",
        callback: (id) => {
          layer.close(id);
        },
      },
    ],
  });
};

//数量弹出框回调事件
const quntiltyAction = ref([
  {
    text: "确定",
    callback: () => {
      console.log("修改数量", selectedProduct.value.number);
      //商品数量为零是要考虑是否要删除商品还是取消输入操作
      if (selectedProduct.value.number == 0) {
        layer.confirm("数量为0，是否要删除该商品？", {
          btn: [
            {
              text: "是",
              callback: (id) => {
                deleteProduct(selectedProduct.value);
                layer.close(id);
              },
            },
            {
              text: "否",
              callback: (id) => {
                // layer.msg("坐着看");
                //将原来的商品数量还原
                selectedProduct.value.number =
                  selectedProduct.value.oldQuantilty;
                layer.close(id);
              },
            },
          ],
        });
      } else {
        //计算商品金额
        computerAllMount(selectedProduct.value);
      }
      quantiltyVisible.value = false;
    },
  },
  {
    text: "取消",
    callback: () => {
      quantiltyVisible.value = false;
    },
  },
]); //修改数量回调方法

//计算商品总金额
const computerAllMount = (p) => {
  home_order_db.value.goods_li.map((item) => {
    if (item.goods_dbid == p.goods_dbid) {
      item.prc_sale_actual_sum = XEUtils.multiply(p.number, p.prc_sale);
      item.number = p.number;
    }
  });
  //修改库存
  // products.value.map((item) => {
  //   if (item.id == p.id) {
  //     item.inventoryNum = XEUtils.subtract(item.inventoryNum, p.quantilty);
  //   }
  // });
  selectedProduct.value = null;
};

//删除商品
const deleteProduct = (p) => {
  console.log("删除", p);
  //1.删除购物车列表
  home_order_db.value.goods_li = home_order_db.value.goods_li.filter(
    (item) => item.goods_dbid != p.goods_dbid
  );
  //2.商品列表库存还原
  // products.value.map((item) => {
  //   if (item.id == p.id) {
  //     item.inventoryNum = XEUtils.add(p.inventoryNum, p.oldQuantilty);
  //   }
  // });
  //3.将选中商品清空
  selectedProduct.value = null;
};

const selectedProduct = ref(null);
const products = ref([
  {
    goods_dbid: 1, //商品id
    barcode: "111111111", //条码
    goods_name: "可口可乐",
    prc_sale: 2.5, //原价
    prc_sale_actual: 2.4, //零售价
    unit_pack: "A", //是否大单位
    in_code: "111111", //录入码
    unit: "听",
    remark: "备注",
    img: "https://img10.360buyimg.com/n7/jfs/t1/114101/1/1035/122068/5d3333e0E23380449/0",
  },
  {
    goods_dbid: 2, //商品id
    barcode: "22222222", //条码
    goods_name: "百事可乐",
    prc_sale: 3, //原价
    prc_sale_actual: 2.5, //零售价
    unit_pack: "A", //是否大单位
    in_code: "2222222", //录入码
    unit: "听",
    remark: "备注",
    img: "https://img10.360buyimg.com/n7/jfs/t1/114101/1/1035/122068/5d3333e0E23380449/0",
  },
]);

//选项卡tab_a
const tab_a_model = ref("1");

// 打印服务数据包
const printerSYS = ref({
  printer_checked_name: "none", //选中的打印机名
  printer_List: [
    { label: "打印关闭", value: "none" },
    { label: "刷新打印机", value: "refresh" },
  ], //打印机列表
  clientInfo: {}, //客户系统信息
});

// 打印体数据
const print_html = ref({
  header: "<h4 style='text-align: center;'>页头</h4><br>", //页头
  body: "",
  footer: "<br><h5 style='text-align: center;'>页脚</h5>", //页脚
});

// socket - 打印机通讯
const socket = io("http://localhost:17521", {
  autoConnect: false, //自动链接 false时要调用socket.connect 主动链接
  transports: ["websocket"],
  auth: {
    token: "", // 在此处填入你 client 设置的 token，缺省可留空
  },
});

// 监听返回-连接接通
socket.on("connect", () => {
  // printerSYS.value.connect = true;
  console.log("连接接通");
});
// 监听返回-连接断开
socket.on("disconnect", (res) => {
  // printerSYS.value.connect = false;
  console.log("连接断开", res);
});
// 监听返回-客户系统信息
socket.on("clientInfo", (res) => {
  // printerSYS.value.clientInfo = res;
  // console.log("客户系统信息", res);
});

// 监听返回-打印机列表
socket.on("printerList", (res) => {
  // console.log("打印机列表", res);
  printerSYS.value.printer_List = [];
  printerSYS.value.printer_List.push(
    { label: "打印关闭", value: "none" },
    { label: "刷新打印机", value: "refresh" }
  );

  let label_status = ""; //打印机的当前状态
  let label_isDefault = ""; //默认打印机
  let label_disabled = false; //是否禁用
  res.forEach((item, index) => {
    // name string - 操作系统理解的打印机名称。
    // displayName string - 打印预览中显示的打印机名称。
    // description string - 任务描述。
    // status number - 打印机的当前状态。
    // isDefault boolean - 是否将此的打印机设置为操作系统的默认打印机。
    // console.log("数组行", index, item);
    if (item.status == 1) {
      label_status = "[在线]";
    } else {
      label_status = "[脱机]";
    }

    if (item.isDefault == true) {
      label_isDefault = "[默认]";
    } else {
      label_isDefault = "";
    }
    printerSYS.value.printer_List.push({
      label: label_status + label_isDefault + item.name,
      value: item.name,
      disabled: label_disabled,
    });
  });
});

//监听返回-打印回调-成功
socket.on("success", (res) => {
  console.log(res);
  console.log("打印回调-success");
});
//监听返回-打印回调-失败
socket.on("error", (res) => {
  console.log(res);
  console.log("打印回调-error");
});

// 主动获取
const printerList = () => {
  socket.emit("getClientInfo"); //客户端信息
  socket.emit("refreshPrinterList"); //请求刷新打印机列表
};
// 打印机选择器点击
function change_PrinterList(e) {
  console.log(e);
  if (e == "none") {
    printerSYS.value.printer_checked_name = "none"; //选中的打印机名
  } else if (e == "refresh") {
    socket.emit("refreshPrinterList"); //请求刷新打印机列表
    printerSYS.value.printer_checked_name = "none"; //选中的打印机名
  } else {
    printerSYS.value.printer_checked_name = e; //选中的打印机名
  }
}
// 发送打印
function TO_printer() {
  if (printerSYS.value.printer_checked_name == "none") {
    console.log("发送打印中断，请选择正常的打印机。当前打印机：", printerSYS.value.printer_checked_name);
    return;
  }
  let html = "";
  html = print_html.value.header + print_html.value.body + print_html.value.footer; //打印的html字符串
  console.log("打印的html字符串", html);

  let order_goods = [];
  order_goods = home_order_db.value.goods_li;
  console.log("商品列表", home_order_db.value.goods_li);

  order_goods.forEach((item, index) => {
    console.log(item);
  });

  let templateId = "1"; //模板id
  let printer = printerSYS.value.printer_checked_name; //打印机名称
  let pageSize = { height: 80 * 1000, width: 48 * 1000 }; //纸张
  return;

  socket.emit("news", {
    html, //打印的html字符串
    templateId, //模板id
    printer, //打印机名称
    pageSize, //打印纸张大小 { height: 80 * 1000, width: 60 * 1000 } 可为空，缺省默认使用打印机默认纸张
  });
  // console.log("未连接客户端！");
  // window.open("hiprint://");
}

// 接收子组件支付回调数据
const pay_res = (res) => {
  console.log("接收子组件支付回调数据", res);
  // click_LI("打印");
};
const windowClose = (res) => {
  console.log("接收子组件数据", res);
  layer.open({
    type: "0",
    title: "提示",
    content: "是否离开结算？",
    closeBtn: false,
    shadeClose: false,
    btn: [
      {
        text: "离开",
        callback: (id) => {
          layer.close(id);
          window_pay_show.value = !window_pay_show.value; //组件弹窗关闭
        },
      },
      {
        text: "取消",
        callback: (id) => {
          layer.close(id);
        },
      },
    ],
  });
};

// 点击
const click_LI = (res) => {
  if (res == "打印") {
    console.log("点击了-打印");
    print_html.value.body = "打印测试";
    TO_printer(); //发送打印
  } else if (res == "历史单") {
    window_show_past_order.value = !window_show_past_order.value
    past_order_http_li();//历史单列表获取
  } else if (res == "开新单") {
    home_order_new();//开新单
  } else if (res == "测试") {
    console.log("点击了-测试");
  } else {
  }
};

// 历史单窗口显示
//列表
const window_show_past_order = ref(false);
// 历史单窗口控制按键
const btn_past_order = ref(
  [{
    text: "确定",
    callback: () => {
      console.log("确定");
    },
  },
  {
    text: "取消",
    callback: () => {
      window_show_past_order.value = !window_show_past_order.value
    },
  }]
)
/** 历史单窗口-列表-表格字段 */
const Past_Order_List_columns = ref([]);

/** 历史单窗口-列表-表格数据 */
const Past_Order_List_dataSource = ref([]);

//详细内容窗口
const window_show_past_order_content = ref(false);
const btn_past_order_content = ref(
  [{
    text: "引用",
    callback: () => {
      console.log("引用订单", order_db.value.dbid);
      home_order(order_db.value.dbid);// 引入当前操作的销售单

    },
  },
  {
    text: "取消",
    callback: () => {
      window_show_past_order_content.value = !window_show_past_order_content.value
      tab_past_order_content.value = "order_db_goods";//选项卡激活id
      order_db.value = {}
      order_db_alias.value = {}

    },
  }]
)


// 选项卡激活id
const tab_past_order_content = ref("order_db_goods");
// 选项卡切换
const change_tab_past_order_content = (id) => {
  // console.log("选项卡切换", id);
};
// 激活的选项卡-单头信息
const order_db = ref({});
// 激活的选项卡-单头字段别名
const order_db_alias = ref({});
// 激活的选项卡-商品信息-表格字段
const past_order_goods_columns = ref([]);
// 激活的选项卡-商品信息-表格数据
const past_order_goods_dataSource = ref([]);
// 激活的选项卡-支付信息-表格字段
const past_order_pay_columns = ref([]);
// 激活的选项卡-支付信息-表格数据
const past_order_pay_dataSource = ref([]);

// 表格行单击
const past_order_row = (row) => {
  // console.log("表格行单击", row);
  window_show_past_order_content.value = !window_show_past_order_content.value
  past_order_http_id(row.dbid);//历史单-获取一条单据信息
};
// 历史单-获取列表
const past_order_http_li = async () => {
  const res = await HTTP_pastOrderList({
    'list_rows': 100, // 每页数量
    'page': 1, // 当前页
  });
  // console.log("获取POS销售单列表", res);
  Past_Order_List_columns.value = res.Past_Order_List_columns
  Past_Order_List_dataSource.value = res.Past_Order_List_dataSource.data
}
// 历史单-获取一条单据信息
const past_order_http_id = async (dbid) => {
  // console.log("点击一条单据的信息", dbid);
  const res = await HTTP_pastOrderId({
    'dbid': dbid,
  });
  // console.log("历史单-获取一条单据信息-HTTP回调", res);
  order_db.value = res.order_db// 激活的选项卡-单头信息
  order_db_alias.value = res.order_db_alias// 激活的选项卡-单头字段别名

  past_order_goods_columns.value = res.past_order_goods_columns// 激活的选项卡-商品信息-表格字段
  past_order_goods_dataSource.value = res.past_order_goods_dataSource// 激活的选项卡-商品信息-表格数据

  past_order_pay_columns.value = res.past_order_pay_columns// 激活的选项卡-支付信息-表格字段
  past_order_pay_dataSource.value = res.past_order_pay_dataSource// 激活的选项卡-支付信息-表格数据
}



// 引入当前操作的销售单
const home_order = async (dbid) => {
  console.log("当前操作的销售单", dbid);
  layer.load(0, { time: 3000 })
  const res = await HTTP_homeOrderId({
    'dbid': dbid,
  });
  console.log("引入当前操作的销售单 HTTP回调", res);
  home_order_db.value.dbid = res.db.dbid;//当前销售单号
  home_order_db.value.sign = res.db.sign;//当前销售单签名串
  home_order_db.value.goods_li = res.goods_li;//商品列表
  console.log("当前操作的销售单----", home_order_db.value);
  layer_window_closeAll();//layer弹窗全部关闭
}
/** layer弹窗全部关闭 */
const layer_window_closeAll = () => {
  layer.closeAll();
  window_show_past_order.value = false;
  window_show_past_order_content.value = false;

}

const QR_val = ref("条码"); //条码输入框-绑定值
// const QR_ref = ref({}); //条码输入框-绑定焦点

// 商品列表块列配置
const columns = [
  // { title: "行", width: "50px", type: "number" },
  {
    title: "条码",
    align: "center",
    width: "80px",
    key: "barcode",
    customSlot: "barcode",
    totalRow: false,
  },
  {
    title: "品名",
    align: "center",
    width: "auto",
    key: "goods_name",
    totalRow: false,
  },
  {
    title: "数量",
    align: "center",
    width: "50px",
    key: "number",
    customSlot: "number",
    totalRow: true,
  },

  {
    title: "实价",//实际零售价
    align: "center",
    width: "50px",
    key: "prc_sale_actual",
    customSlot: "prc_sale_actual",
    totalRow: false,
  },
  // {
  //   title: "档案零售价",
  //   align: "center",
  //   width: "80px",
  //   key: "prc_sale_actual",
  //   customSlot: "prc_sale_actual",
  //   totalRow: true,
  // },
  {
    title: "小计",
    align: "center",
    width: "80px",
    key: "prc_sale_actual_sum",
    customSlot: "prc_sale_actual_sum",
    totalRow: true,
  },

  {
    title: "操作",
    width: "40px",
    customSlot: "operator",
    key: "operator",
  },
];
// 表格行样式
const rowStyle = (rowdb, rowIndex) => {
  // console.log("行样式-行数据", rowIndex, rowdb);
  // console.log("行索引", rowIndex);
  // return "background-color:var(--global-neutral-color-1);color: #FF6C37;text-align: left !important; ";
};
//列字段提示
const tooltip_content = (row) => {
  // console.log("列字段提示-行数据", row);
  // return "……";
};
//商品点击
const selectProduct = (e) => {
  console.log("商品点击", e);
  //添加商品,通过id判断是否存在于购物车,存在就数量加一,不存在就添加一行,(是否需要验证库存,并提示)
  // if (e.inventoryNum < 1) {
  //   layer.msg("库存不足", { icon: 5 });
  //   return;
  // }
  // if (e.inventoryNum < 3) {
  //   layer.msg("库存不足,请及时补充", { icon: 7 });
  // }
  /** 当前商品列表 */
  const selectedList = home_order_db.value.goods_li;
  //判断是否在购物车中
  let flag = selectedList.some((item) => {
    return item.goods_dbid == e.goods_dbid;
  });
  if (selectedList.length < 1 || !flag) {
    e.number = 1;
    e.prc_sale_actual_sum = XEUtils.multiply(e.prc_sale, e.number);
    selectedList.push(e);
  } else {
    selectedList.map((item) => {
      if (item.goods_dbid == e.goods_dbid) {
        item.number++;
        item.prc_sale_actual_sum = XEUtils.multiply(item.prc_sale, item.number);
      }
    });
  }

  console.log("当前商品列表", home_order_db.value.goods_li);
};
//点击修改数量表格触发
const changeQuantilty = (data) => {
  selectedProduct.value = { ...data, oldQuantilty: data.number };
  quantiltyVisible.value = true;
};
//修改数量触发事件
const quantiltyChange = (val) => {
  /**
   * 1.提示不能为0
   * 2.为空默认设置为0
   * 3.不能超过库存
   */
  if (!val) {
    layer.msg("数量不能为空", { icon: 5 });
    selectedProduct.value.number = 0;
  } else if (val.startsWith("0")) {
    selectedProduct.value.number = parseInt(val, 10); // 第二个参数10表示基数是十进制
  }

  console.log("quantiltyChange", selectedProduct.value);
  // 所有数量
  // const all = XEUtils.add(
  //   selectedProduct.value.oldQuantilty,
  //   selectedProduct.value.inventoryNum
  // );
  // if (val > all) {
  //   layer.msg("库存不足", { icon: 5 });
  //   //将剩余+已选中的才是所有
  //   selectedProduct.value.quantilty = all;
  // } else {
  //   }
  selectedProduct.value.number = val;
};

//点击键盘的值
const clickKey = (key) => {
  // console.log("key-->>",key);
};
//点击键盘时数字的值
const clickNumber = (key) => {
  // console.log("key-->>",key);
};


//条码输入框-绑定值
const changeQR_val = () => {
  if (QR_val.value.length > 9) {
    layer.msg("条码长度为9位,请查询后再输入!", { icon: 5 });
    QR_val.value = QR_val.value.substring(0, 9);
  }
};

// 条码输入框-绑定值-事件
function QR_event() {
  console.log("QR", QR_val.value);
  //1.查询所有商品,是否存在条码
  const product = products.value.find((item) => {
    return item.barcode == QR_val.value;
  });

  if (!product) {
    layer.msg("条码不存在,请查询后再输入!", { icon: 5 });
    QR_val.value = "";
  } else {
    //2.添加到购物车
    selectProduct(product);
  }
  // Add();
}

// 弹出键盘
function QR_keyboard() {
  showKeyboard1.value = ! showKeyboard1.value
  console.log("弹出键盘",showKeyboard1.value);

}



// 结算按钮-点击-保存订单
const settlement = async () => {
  console.log("结算按钮-点击-保存订单");
  //点结算按钮,需要先保存到后端
  //  保存订单
  const res = await HTTP_saveOrder({
    type: "A1",//单据类型_A1销售B1退货
    operation: "A",//操作类型_A结算保存B挂单保存
    dbid: home_order_db.value.dbid,//当前销售单号
    sign: home_order_db.value.sign,//当前销售单号签名串
    remark: "单据备注88",//单据备注
    goods_db: home_order_db.value.goods_li,//要保存的商品列表
  });

  // console.log("保存订单-HTTP回调", res);
  // console.log("前端home_order_db", home_order_db.value);
  if (res.code == 200) {
    window_pay_show.value = true;
  } else {
    layer.msg(res.msg, { icon: 5 });
  }

};
// 条码点击
function barcode_c(res) {
  console.log("条码点击", res);
  Del(res);
}

// 删除行
const Del = (res) => {
  console.log("删除行", res);
  layer.confirm("确定删除此条数据？" + res.goods_dbid, {
    title: res.barcode + " " + res.goods_name,
    shadeClose: true,
    btn: [
      {
        text: "确定",
        callback: () => {
          home_order_db.value.goods_li.forEach((item, index, array) => {
            if (item.goods_dbid === res.goods_dbid) {
              home_order_db.value.goods_li.splice(index, 1);
            }
          });
          layer.closeAll();
        },
      },
      {
        text: "取消",
        callback: () => {
          layer.closeAll();
        },
      },
    ],
  });
};
document.onselectstart = new Function("event.returnValue=false"); //禁止鼠标选中文字
document.oncontextmenu = new Function("event.returnValue=false"); //禁止鼠标右键
// 监听键盘按键
document.addEventListener("keydown", function (e) {
  console.log("按键", e.key);
  // if (e.key == "F12") {
  // e.preventDefault(); // 如果按下键F12,阻止事件
  // }

  if (e.key == "ArrowDown") {
    QR_val.value = ""; //条码输入框-绑定值
    // QR_ref.value.focus({}); //条码输入框-绑定焦点
  }
});

document.addEventListener("mousemove", updateMousePosition); //监听鼠标移动
window.addEventListener("mousedown", handleMousedown); //监听鼠标按下
window.addEventListener("mouseup", handleMouseup); //监听鼠标抬起
// window.addEventListener('keydown', handlekeydown)//监听键盘按下
function updateMousePosition(event) {
  // mousePosition.x = event.clientX;
  // mousePosition.y = event.clientY;
}
function handleMousedown(e) {
  if (e.button == 0) {
    // console.log('鼠标左键按下')
  }
  if (e.button == 1) {
    // console.log('鼠标滚动键按下')
  }
  if (e.button == 2) {
    // console.log('鼠标右键按下')
  }
  // console.log("坐标", e.pageX, e.pageY)
}

function handleMouseup(e) {
  if (e.button == 0) {
    // console.log('鼠标左键抬起')
  }
  if (e.button == 1) {
    // console.log('鼠标滚动键抬起')
  }
  if (e.button == 2) {
    // console.log('鼠标右键抬起')
  }
  // console.log("坐标", e.pageX, e.pageY)
}
function handlekeydown(e) {
  console.log("监听键盘按下", e.key);
}
/** 开新单 */
const home_order_new = async () => {
  // console.log("开新单");
  const res = await HTTP_newDbid({
    operator: "工号1001",
  });
  console.log("新单号", res);

  if (res.code == 200) {
    home_order_db.value.dbid = res.db.dbid;//当前销售单号
    home_order_db.value.sign = res.db.sign;//当前销售单签名串
    home_order_db.value.goods_li = [];//商品列表
  } else {
    layer.msg(res.msg, { icon: 5 });
  }
};



// 生命周期钩子
onMounted(() => {
  // QR_ref.value.focus({}); //条码输入框-绑定焦点
  QR_val.value = ""; //条码输入框-绑定值
  // home_order_new();//开新单
  // socket.connect(); //连接socket
});
</script>




<style lang="less" scoped>
* {
  /* 禁选中文字 */
  user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
  padding: 0;
  margin: 0;
}

/* 滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 8px;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0);
  background-color: #b3b3b3;
}

.example .layui-footer,
.example .layui-header {
  line-height: 60px;
}

.example .layui-side {
  display: flex;
  /* background: #36cc61; */
  justify-content: center;
}

.example .layui-body {
  display: flex;
  /* background: #5FB878; */
}

.body2 {
  display: flex;
  overflow-y: auto;
  overflow-x: hidden;
  height: calc(100vh - 252px);
  flex-wrap: wrap;
  align-items: flex-start;
  align-content: flex-start;
}

.body2 .vc {
  background: rgb(95, 107, 216) !important;
  width: 132px;
  height: 80px;
  margin: 0 0 4px 4px;
  padding: 0 4px;
  border-radius: 4px;
}

.body2 .vc span {
  background: rgb(95, 107, 216) !important;
}

.body2 .vc .vc1 {
  display: block;
  background: rgb(238, 173, 234) !important;
  height: 20px;
  line-height: 20px;
  text-align: center;
}

.body2 .vc .vc2 {
  background: rgb(185, 185, 189) !important;
  height: 40px;
  display: block;
}

.body2 .vc .vc3 {
  display: flex;
  background: rgb(95, 107, 216) !important;
  height: 20px;
  line-height: 20px;
}

.body2 .vc .vc3a {
  background: rgb(169, 170, 172) !important;
  flex-grow: 1;
}

.body2 .vc .vc3b {
  background: rgb(100, 103, 133) !important;
  flex-grow: 1;
  text-align: center;
}

.vv789 {
  display: flex;
  display: -webkit-flex;
  padding: 0 0 0 6px;
  line-height: 30px;
  justify-content: space-between;
  overflow-y: auto;
  overflow-x: hidden;
}

.vv789 span {
  width: 32%;
  background: rgb(199, 168, 155);
}

.cc {
  display: flex;
  height: calc(100vh - 64px);
  padding-top: 2px;
  overflow-y: auto;
  overflow-x: hidden;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: center;
  align-content: flex-start;
}

.cc span {
  display: grid;
  width: 60px;
  height: 45px;
  margin: 2px 0;
  color: #ffffff;
  background: #ff5722 !important;
  justify-content: center;
  align-content: center;
  border-radius: 4px;
}

.dd {
  display: grid;
  overflow-y: hidden;
  overflow-x: auto;
  grid-template-columns: repeat(auto-fill, 80px);
  grid-template-rows: repeat(auto-fill, 60px);
  grid-row-gap: 4px;
  grid-column-gap: 4px;
  min-width: 550px;
}

.dd span {
  display: grid;
  background: #ff5722;
  align-items: center;
  justify-content: center;
  align-content: center;
}

.footer_d {
  display: flex;
  background-color: #d8bdbd;
  padding: 0 10px;
  width: 100%;
}

.footer_d div {
  flex-grow: 1;
}

.p_list {
  display: flex;
  flex-flow: wrap;
  justify-content: space-around;

  .p_main {
    width: 200px;
    height: 180px;
    margin-bottom: 10px;
    border: 1px solid #ff5722;
    border-radius: 5px;

    .p_main_header {
      text-align: center;
      line-height: 20px;
      background: #ffbca7;
      font-size: 16px;
      font-weight: 600;
      font-family: fangsong;
      // width: 200px; /* 设置元素的宽度 */
      width: 100%;
      white-space: nowrap;
      /* 不换行 */
      overflow: hidden;
      /* 控制溢出部分的处理方式 */
      text-overflow: ellipsis;
      /* 显示省略号 */
    }

    .p_main_body {
      width: 100%;
      height: calc(100% - 20px);

      .p_main_body_img {
        height: calc(100% - 20px);
        width: 100%;

        img {
          height: 100%;
          width: 100%;
        }
      }

      .p_main_body_fotter {
        width: 100%;
        height: 20px;
        background-color: #ffbca7;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 600;
        font-family: fangsong;

        span {
          margin: 0 3px;
        }
      }
    }
  }
}

.layui-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .layui-btn {
    padding: 0 15px;
  }

  .btn_foot {
    margin-right: 20px;
  }
}

.t_quantilty_input {
  width: 100%;
  height: 80px;
  line-height: 80px;
  text-align: center;
}



.prc_sale_actual_sum {
  width: 100%;
  text-align: right;
}
</style>
